<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { equipmentListApi, equipmentTypeListAllApi } from '@/api/equipment'
import { borrowApplyApi } from '@/api/borrow'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { ref, unref, reactive, onMounted } from 'vue'
import Borrow from './components/Borrow.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await equipmentListApi({
      pageNo: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.totalCount
    }
  }
})

// 这里定义一个 equipmentTypeOptions 的变量，用于存储 equipmentType 的选项，其值通过 equipmentTypeListAllApi 获取
const equipmentTypeOptions = ref<any[]>([])
// 这里定义一个函数，用于获取 equipmentType 的选项，并赋值给 equipmentTypeOptions
const fetchEquipmentTypeOptions = async () => {
  const res = await equipmentTypeListAllApi()
  equipmentTypeOptions.value = res.data.map((v: any) => ({
    label: v.equipmentTypeName,
    value: v.equipmentTypeId
  }))
}

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

onMounted(() => {
  fetchEquipmentTypeOptions()
})

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'equipmentTypeId',
    label: t('equipmentTable.equipmentTypeId'),
    table: {
      formatter: (row: any) => {
        const found = equipmentTypeOptions.value.find((item) => item.value === row.equipmentTypeId)
        return found?.label || row.equipmentTypeId
      }
    },
    search: {
      component: 'Select',
      componentProps: {
        options: equipmentTypeOptions,
        on: {
          change: (value: string) => {
            console.log(value)
          }
        }
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        options: equipmentTypeOptions,
        on: {
          change: (value: string) => {
            console.log(value)
          }
        }
      }
    },
    detail: {
      hidden: false,
      formatter: (row: any) => {
        const found = equipmentTypeOptions.value.find((item) => item.value === row)
        return found?.label || row
      }
    }
  },
  {
    field: 'name',
    label: t('equipmentTable.name'),
    search: {
      hidden: false
    },
    form: {
      hidden: false
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'brand',
    label: t('equipmentTable.brand'),
    search: {
      hidden: false
    },
    form: {
      hidden: false
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'model',
    label: t('equipmentTable.model'),
    search: {
      hidden: false
    },
    form: {
      hidden: false
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'price',
    label: t('equipmentTable.price'),
    search: {
      hidden: true
    },
    form: {
      component: 'InputNumber',
      value: 0
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'stockQuantity',
    label: t('equipmentTable.stockQuantity'),
    search: {
      hidden: true
    },
    form: {
      component: 'InputNumber',
      value: 0
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'createTime',
    label: t('common.createTime'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'updateTime',
    label: t('common.updateTime'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <BaseButton type="primary" onClick={() => action(data.row)}>
                {t('equipmentTable.borrow')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<TableData | null>(null)

const action = (row: TableData) => {
  dialogTitle.value = t('equipmentTable.borrow')
  currentRow.value = row
  dialogVisible.value = true
}

const borrowRef = ref<ComponentRef<typeof Borrow>>()

const saveLoading = ref(false)
const save = async () => {
  const borrow = unref(borrowRef)
  const formData = await borrow?.submit()
  console.log('formData=', formData)
  if (formData) {
    saveLoading.value = true
    const res = await borrowApplyApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Borrow ref="borrowRef" :detail-schema="allSchemas.detailSchema" :current-row="currentRow" />

    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('equipmentTable.borrowApply') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
